package cn.xyy.system.service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.xyy.system.dao.RoleDao;
import cn.xyy.web.AuthUserHolder;
import cn.xyy.common.domain.system.auth.Role;
import cn.xyy.common.domain.system.auth.RoleDept;
import cn.xyy.common.domain.system.auth.RolePermission;
import cn.xyy.common.domain.system.auth.RoleVO;
import cn.xyy.common.constant.DataScopeType;
import cn.xyy.common.utils.BeanUtils;
import cn.xyy.common.utils.DateUtils;
import cn.xyy.common.utils.StringUtils;
import cn.xyy.common.exception.SystemException;
import cn.xyy.common.domain.mvc.Page;

/**
 * 角色业务
 * 
 * @author xyy
 *
 */
@Service
public class RoleService {

	@Autowired
	private RoleDao roleDao;

	public Page<Role> getRolePage(RoleVO vo) {
		return roleDao.selectPage(vo);
	}

	public List<Role> getEnableRoleList() {
		return roleDao.select(new Role().setStatus(1));
	}

	public List<Role> getRoleListByUser(String userId) {
		if (StringUtils.isBlank(userId)) {
			throw new SystemException("userId不能为空");
		}
		return roleDao.selectByUser(userId);
	}

	@Transactional(value = "baseTransactionManager")
	public void add(RoleVO vo) throws SystemException {
		if (StringUtils.isBlank(vo.getName())) {
			throw new SystemException("角色名不能为空");
		}
		Role existRole = roleDao.selectOne(new Role().setName(vo.getName()));
		if (existRole != null) {
			throw new SystemException("角色已存在");
		}
		Role roleInfo = new Role();
		BeanUtils.copyProperties(vo, roleInfo);
		roleInfo.setCreator(AuthUserHolder.getUserInfo().getUsername());
		roleInfo.setCreateTime(DateUtils.getDateTime());

		int result = roleDao.insertReturnAutoIncrement(roleInfo);

		if (vo.getPermIdList() != null && vo.getPermIdList().length > 0) {
			vo.setId(String.valueOf(result));
			saveRelationPermission(vo);
		}
	}

	@Transactional(value = "baseTransactionManager")
	public void update(RoleVO vo) {

		if (vo.getId() == null) {
			throw new SystemException("保存数据不能为空");
		}
		if (StringUtils.isBlank(vo.getName())) {
			throw new SystemException("角色名不能为空");
		}
		Role roleInfo = roleDao.selectOne(new Role().setId(vo.getId()));
		if (roleInfo == null) {
			throw new SystemException("未查询到角色信息");
		}
		BeanUtils.copyProperties(vo, roleInfo);
		roleInfo.setUpdater(AuthUserHolder.getUserInfo().getUsername());
		roleInfo.setUpdateTime(DateUtils.getDateTime());

		roleDao.update(roleInfo);

		RolePermission rp = new RolePermission();
		rp.setRoleId(vo.getId());
		roleDao.delete(rp);
		if (vo.getPermIdList() != null && vo.getPermIdList().length > 0) {
			saveRelationPermission(vo);
		}
	}

	public void saveRelationPermission(RoleVO role) {
		List<RolePermission> rpList = Arrays.stream(role.getPermIdList()).map(e -> {
			RolePermission rp = new RolePermission();
			rp.setRoleId(role.getId());
			rp.setPermId(e);
			return rp;
		}).collect(Collectors.toList());
		roleDao.batchInsert(rpList);
	}

	@Transactional(value = "baseTransactionManager")
	public void delete(String code) {
		if (code == null) {
			throw new SystemException("删除条件不能为空");
		}
		Role role = new Role();
		role.setId(code);
		int result = 0;
		// 删除角色本身
		result = roleDao.delete(role);
		if (result < 0) {
			throw new SystemException("执行失败");
		}

		// 删除角色对应的权限
		roleDao.delete(new RolePermission().setRoleId(code));
	}

	@Transactional(value = "baseTransactionManager")
	public void saveRelationDataScope(RoleVO role) {
		if (role == null) {
			throw new SystemException("条件不能为空");
		}
		if (role.getId() == null || role.getDataScopeType() == null) {
			throw new SystemException("条件不能为空");
		}
		Role roleInfo = roleDao.selectOne(new Role().setId(role.getId()));
		if (roleInfo == null) {
			throw new SystemException("角色不存在");
		}

		// 自定义数据权限
		if (DataScopeType.customize.equals(role.getDataScopeType())) {
			if (role.getDataScopeList() == null || role.getDataScopeList().length == 0) {
				throw new SystemException("自定义数据权限不能为空");
			}
			roleDao.delete(new RoleDept().setRoleId(role.getId()));

			List<RoleDept> rdList = Arrays.stream(role.getDataScopeList()).map(e -> {
				RoleDept rd = new RoleDept();
				rd.setRoleId(role.getId());
				rd.setDeptId(e);
				return rd;
			}).collect(Collectors.toList());

			roleDao.batchInsert(rdList);
		}
		roleInfo.setDataScopeType(role.getDataScopeType());
		roleDao.update(roleInfo);
	}

	public List<String> getDataScopeListByRole(String roleId) {
		if (roleId == null) {
			throw new SystemException("条件不能为空");
		}
		return roleDao.selectRoleDetp(roleId);
	}

	public void updateState(RoleVO role) {
		if (role.getId() == null) {
			throw new SystemException("id为空");
		}
		roleDao.updateState(role.getId(), role.getStatus());
	}
}
